package com.zzz.poker.netty.configuration;

import com.zzz.poker.netty.handler.WebSocketHandler;
import com.zzz.poker.properties.WebSocketProperties;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * WebSocket Channel 初始化
 */
@Component
public class WebSocketInitializer extends ChannelInitializer<SocketChannel> {
    private final WebSocketProperties properties;
    private final WebSocketHandler webSocketHandler;

    public WebSocketInitializer(WebSocketProperties properties, WebSocketHandler webSocketHandler) {
        this.properties = properties;
        this.webSocketHandler = webSocketHandler;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        
        // HTTP 编解码器
        pipeline.addLast(new HttpServerCodec());
        // 支持大数据流
        pipeline.addLast(new ChunkedWriteHandler());
        // HTTP 消息聚合器
        pipeline.addLast(new HttpObjectAggregator(65536));
        // WebSocket 压缩支持
        pipeline.addLast(new WebSocketServerCompressionHandler());
        // WebSocket 协议处理器
        pipeline.addLast(new WebSocketServerProtocolHandler(
                properties.getPath(), 
                null, 
                true, 
                properties.getMaxFrameSize()));
        // 心跳检测
        pipeline.addLast(new IdleStateHandler(
                properties.getReaderIdleTime(), 
                properties.getWriterIdleTime(), 
                properties.getAllIdleTime(), 
                TimeUnit.SECONDS));
        // 自定义 WebSocket 处理器
        pipeline.addLast(webSocketHandler);
    }
}